package com.hdkj.educenter.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.hdkj.commonutils.JwtUtils;
import com.hdkj.commonutils.R;
import com.hdkj.educenter.client.EduTimeStampClient;
import com.hdkj.educenter.entity.UcenterMember;
import com.hdkj.educenter.entity.vo.timestampVo;
import com.hdkj.educenter.service.UcenterMemberService;
import com.hdkj.handler.GuiliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Optional;

//@CrossOrigin
@Controller  //只是请求地址，不需要返回数据
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;

    @Autowired
    private EduTimeStampClient eduTimeStampClient;

    //2 获取扫描人信息，添加数据
    @GetMapping("callback")
    public String callback(@RequestParam("app_id") String APP_ID, @RequestParam("auth_code") String code) throws AlipayApiException {
        String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApWhlU/I8tq4+d0kkCM8vOrzZw4H0sN85LI4GdAz81LrtuDy3oGFvloMqXgUl4oZQNykxVLQNtpjL1RYWLC/11yk5jJAhXyjAfcbVuvJ7NWoxq/FRl0DjZn+4fSbjHUo5TSkaunuo5KKsMbGuRm4yHfQ1qyAEiLL+JtjamxZj8g1unaNTZqCrk6t+CqvCZoP+/sQFd94qEqOwbxxfjfvyhmRTVV+/Ip8Ryb590bYiPJcBe6w3O6CUqV/+SUscn6TfC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Il52aZJiMctg37yMC+0y7zswBTdtlUFOKhhgjSpbMqTYfWBOcrGSOfZd2xmDNYJ5gxVTPBVXtrO/l6Yg94chMYE2X+mv8W5f72KL5CxD1sF3OnjObVZlyjlr5Oj8a2FUZzYQKBgE6q1jgvVEWlwcKhf8RuBWpKwaYMiJCVrMb5mvsxPWETge/Rei9CgawiPcQzKA6cUkoxewRD0+mRsK+tOgp+GeA8izbGSwOrXsDBh8JrHGXXd6oxso35/veHMT5tbfnEO3C2gR8MyWUMEfTchQQikSFwrS+nt0zzSV+MEucL3ooBAoGAW85T1+rdtk0+7+8XdJu0kPk50PwHhmjLGTsqYKvdaVxx4g+woUl9HtEcdZr438SQcuxh7IhltZZlYuxsta/WF6Q2plN/shi4xZFKOxtRuz0ADEebNu9sWp6bRIW6WaO9y2355jpDKb7Af5dm/IMLCVTWINZgV1nqU7RFtJUzPIECgYEA0ZswC36OsqJpzUvfu+9f2E7Un29E1LWWALBJLiD22Wu9cM1JAFG3qEwqfKQQOn3sAL0OFQk/vs+EizFXRL6jJ98Ct2Yq6MDAPR3bvwfqUlwSlcFvV71vpqf5fmDBJc3WA0NXUYDdEp+YXHJQVk4Y26kl1Zzm+k82ZmV9v2cHKiE=";
        String CHARSET = "utf-8";
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2");
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        AlipayUserInfoShareRequest userrequest = new AlipayUserInfoShareRequest();
        request.setCode(code);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            String accessToken = oauthTokenResponse.getAccessToken();
            AlipayUserInfoShareResponse userinfo = alipayClient.execute(userrequest, accessToken);
            String nickName = userinfo.getNickName();
            String photo = userinfo.getAvatar();
            String openid = userinfo.getUserId();
            String phone = userinfo.getPhone();
            Optional<UcenterMember> optional = Optional.ofNullable(memberService.getOpenIdMember(openid));
            UcenterMember ucenterMember = new UcenterMember();
            if (!optional.isPresent()){
                ucenterMember.setNickname(nickName);
                ucenterMember.setOpenid(openid);
                ucenterMember.setAvatar(photo);
                ucenterMember.setMobile(phone);
                memberService.save(ucenterMember);

                timestampVo timestampVo = new timestampVo();
                timestampVo.setContent("这是您第一次走进信工开源的世界！");
                timestampVo.setTitle("第一次注册");
                timestampVo.setTime(new Date());
                eduTimeStampClient.saveTs(timestampVo);

            }
            String jwtToken = JwtUtils.getJwtToken(memberService.getOpenIdMember(openid).getId(), memberService.getOpenIdMember(openid).getNickname());
            //最后：返回首页面，通过路径传递token字符串
            return "redirect:http://localhost:3000?token="+jwtToken;

        } catch (AlipayApiException e) {
            //处理异常
            throw new GuiliException(20001,"登录失败");
        }
    }

    //1 生成支付宝扫描二维码
    @GetMapping("login")
    @ResponseBody
    public R getWxCode() {
        String appid = "2021000118648268";
        String redirect_uri = "http://10.28.5.130:8150/api/ucenter/wx/callback";//扫描成功后回调地址
        try {
            redirect_uri = URLEncoder.encode(redirect_uri, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = "https://openauth.alipaydev.com/oauth2/publicAppAuthorize.htm?app_id=" + appid + "&scope=auth_user&redirect_uri=" + redirect_uri;
        return R.ok().data("urls",url);
    }
}
